package com.suse.service.community.mvc.interceptor;

import cn.hutool.core.util.ObjectUtil;
import com.suse.common.util.cookie.CookieUtil;
import com.suse.common.util.core.StringUtil;
import com.suse.service.community.entity.LoginTicket;
import com.suse.service.community.entity.User;
import com.suse.service.community.service.UserService;
import com.suse.service.community.util.UserHolder;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <p>
 * 登录拦截器
 * </p>
 *
 * @author 辜玉彬
 * @since 2022-08-30 16:05
 */
@SuppressWarnings("all")
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Resource
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String ticket = CookieUtil.getValue("ticket", request);
        if (StringUtil.isEmpty(ticket)) {
            return true;
        }
        LoginTicket loginTicket = userService.getLoginTicketByTicket(ticket);
        if (ObjectUtil.isNull(loginTicket)) {
            return true;
        }
        if (loginTicket.isValid()) {
            User user = userService.getUserById(loginTicket.getUserId());
            UserHolder.setUser(user);
            // 进行登录认证
            UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(user, user.getPassword(), user.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        User user = UserHolder.getUser();
        if (ObjectUtil.isAllNotEmpty(user,modelAndView)) {
            modelAndView.addObject("loginUser",user);
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.removeUser();
    }

}
